package com.paishen.peiniwan.module.login;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.widget.h.AnvilTextView;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.HttpResp;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.AuthCode;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.frame.widget.InputEditLayout;
import com.paishen.peiniwan.frame.widget.PagerLayout;
import com.squareup.okhttp.Request;

public class RegisterLayout extends FrameLayout {
    private LayoutInflater layoutInflater;
    private ImageView imgBack;
    private AnvilTextView hTextView;
    private PagerLayout layPager;
    private TextView txAuth, txNext;
    private InputEditLayout layEditAuth, layEditPhone, layEditInvite, layEditPwd;
    private View layPartPhone, layPartAuth, layPartPwd;

    private static final int DEFAULT_COUNTDOWN = 60;
    private int countdownTime;

    private String authCode;
    private boolean isPhoneAndInviteChecked, isAuthCodeChecked;

    private ValueAnimator animator;

    static final int STEP_PHONE = 1;
    static final int STEP_AUTH = 2;
    static final int STEP_PWD = 3;
    private int currStep = STEP_PHONE;

    public RegisterLayout(Context context) {
        this(context, null);
    }

    public ImageView setOnRegisterBackClickListener(final View.OnClickListener onRegisterClickListener) {
        imgBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onRegisterClickListener != null && layPager.popToLastContent() == null) {
                    onRegisterClickListener.onClick(v);
                }
            }
        });
        return imgBack;
    }

    public RegisterLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layoutInflater.inflate(R.layout.layout_amazing_register, this);

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // interrupt click event
                BaseUtil.hideSoftInputFromWindowAlways((Activity) getContext());
            }
        });

        hTextView = (AnvilTextView) findViewById(R.id.tx_title);
        hTextView.animateText(context.getString(R.string.register_2));
        layPager = (PagerLayout) findViewById(R.id.lay_pager);
        layPager.setCanTouchable(false);
        layPager.setOnStateChangedListener(new PagerLayout.OnStateChangedListener() {
            @Override
            public void upToCurrent() {
            }

            @Override
            public void backToLast() {
                if (currStep == STEP_PWD) {
                    hTextView.animateText(getContext().getString(R.string.register_input_auth));
                    currStep = STEP_AUTH;
                } else if (currStep == STEP_AUTH) {
                    hTextView.animateText(getContext().getString(R.string.register_2));
                    currStep = STEP_PHONE;
                }
            }

            @Override
            public void touchMove(float progress) {
            }
        });

        FrameLayout.LayoutParams lpBack = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lpBack.setMargins(0, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);
        imgBack = (ImageView) findViewById(R.id.img_back);
        imgBack.setLayoutParams(lpBack);
        imgBack.setEnabled(false);

        txNext = (TextView) findViewById(R.id.tx_next);
        txNext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currStep == STEP_PHONE) {
                    if (TextUtils.isEmpty(layEditPhone.getText()) || layEditPhone.getText().length() != 11) {
                        BaseUtil.showToast(R.string.register_input_phone);
                        return;
                    } else if (!isPhoneAndInviteChecked) {
                        String phone = layEditPhone.getText().toString();
                        String inviteCode = layEditInvite.getText().toString();
                        requestChecksumPhoneAndInviteCode(phone, inviteCode);
                    } else {
                        layPartAuth = layoutInflater.inflate(R.layout.layout_amazing_register_auth, null);
                        layEditAuth = (InputEditLayout) layPartAuth.findViewById(R.id.lay_edit_auth);
                        layEditAuth.setInputType(InputType.TYPE_CLASS_NUMBER);
                        layEditAuth.setText(authCode);
                        layEditAuth.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {
                                isAuthCodeChecked = false;
                            }

                            @Override
                            public void afterTextChanged(Editable s) {
                            }
                        });

                        txAuth = (TextView) layPartAuth.findViewById(R.id.tx_auth);
                        txAuth.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestSendValidCode();
                            }
                        });
                        layPager.pushNewContent(layPartAuth);
                        hTextView.animateText(getContext().getString(R.string.register_input_auth));
                        currStep = STEP_AUTH;
                        if (!isAuthCodeChecked) {
                            if (countdownTime > 0) {
                                refreshValidCountdown();
                            } else {
                                requestSendValidCode();
                            }
                        }
                    }
                } else if (currStep == STEP_AUTH) {
                    if (isAuthCodeChecked) {
                        txAuth.setEnabled(false);
                        layPartPwd = layoutInflater.inflate(R.layout.layout_amazing_register_pwd, null);
                        layEditPwd = (InputEditLayout) layPartPwd.findViewById(R.id.lay_edit_set_pwd);
                        layPager.pushNewContent(layPartPwd);
                        hTextView.animateText(getContext().getString(R.string.register_set_pwd));
                        currStep = STEP_PWD;
                    } else if (TextUtils.isEmpty(layEditAuth.getText())) {
                        BaseUtil.showToast(R.string.register_input_auth);
                        return;
                    } else {
                        requestCheckValidCode();
                    }
                } else {
                    String phone = layEditPhone.getText().toString();
                    String pwd = layEditPwd.getText().toString();
                    String invite = layEditInvite.getText().toString();

                    if (TextUtils.isEmpty(pwd) || pwd.length() < 6) {
                        BaseUtil.showToast(R.string.register_input_set_pwd);
                        return;
                    }

                    Intent intent = new Intent(getContext(), RegisterCompleteActivity.class);
                    intent.putExtra(RegisterCompleteActivity.EXTRA_PHONE, phone);
                    intent.putExtra(RegisterCompleteActivity.EXTRA_PASSWORD, pwd);
                    if (!TextUtils.isEmpty(invite))
                        intent.putExtra(RegisterCompleteActivity.EXTRA_INVITE, invite);
                    getContext().startActivity(intent);
                }
            }
        });


        layPartPhone = layoutInflater.inflate(R.layout.layout_amazing_register_phone, null);
        layEditPhone = (InputEditLayout) layPartPhone.findViewById(R.id.lay_edit_phone);
        layEditPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        layEditPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isPhoneAndInviteChecked = false;
                isAuthCodeChecked = false;
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        layEditInvite = (InputEditLayout) layPartPhone.findViewById(R.id.lay_edit_invite);
        layEditInvite.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isPhoneAndInviteChecked = false;
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        layPager.pushNewContent(layPartPhone, false);

    }


    private void requestSendValidCode() {
        if (txAuth.isEnabled()) {
            String phone = layEditPhone.getText().toString();

            txAuth.setText(R.string.register_get_valicode_1);
            txAuth.setEnabled(false);
            PnwHttpManager.User.sendValidCode(((BaseActivity) getContext()).TAG, phone, "reg", new PnwOkCallbackAdapter<HttpRespData<AuthCode>>() {
                @Override
                public void onResponse(HttpRespData<AuthCode> response, boolean fresh) {
                    super.onResponse(response, fresh);
                    if (response.errcode == C.http.RESULT_SUCCESS) {
                        countdownTime = DEFAULT_COUNTDOWN;
                        refreshValidCountdown();
                        // respAuthCode = response.data.code;
                    } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                            response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                        BaseUtil.showToast(response.errmsg);
                        txAuth.setText(R.string.register_get_valicode);
                        txAuth.setEnabled(true);
                    }
                }

                @Override
                public void onFailure(Request request, Exception e) {
                    super.onFailure(request, e);
                    txAuth.setText(R.string.register_get_valicode);
                    txAuth.setEnabled(true);
                }
            });
        }
    }

    private void requestCheckValidCode() {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(getContext()).create();
        dlgLoading.show();

        final String phone = layEditPhone.getText().toString();
        final String vcode = layEditAuth.getText().toString();
        PnwHttpManager.User.checkValidCode(((BaseActivity) getContext()).TAG, phone, vcode, new PnwOkCallbackAdapter<HttpRespData<AuthCode>>() {
            @Override
            public void onResponse(HttpRespData<AuthCode> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {

                    layPartPwd = layoutInflater.inflate(R.layout.layout_amazing_register_pwd, null);
                    layEditPwd = (InputEditLayout) layPartPwd.findViewById(R.id.lay_edit_set_pwd);
                    layPager.pushNewContent(layPartPwd);
                    hTextView.animateText(getContext().getString(R.string.register_set_pwd));
                    currStep = STEP_PWD;
                    authCode = vcode;
                    isAuthCodeChecked = true;
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private void requestChecksumPhoneAndInviteCode(String phone, String invite) {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(getContext()).create();
        dlgLoading.show();
        PnwHttpManager.User.checksumPhoneAndInviteCode(((BaseActivity) getContext()).TAG, phone, invite, new PnwOkCallbackAdapter<HttpResp>() {
            @Override
            public void onResponse(HttpResp response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    layPartAuth = layoutInflater.inflate(R.layout.layout_amazing_register_auth, null);
                    layEditAuth = (InputEditLayout) layPartAuth.findViewById(R.id.lay_edit_auth);
                    layEditAuth.setInputType(InputType.TYPE_CLASS_NUMBER);
                    layEditAuth.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            isAuthCodeChecked = false;
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                        }
                    });
                    txAuth = (TextView) layPartAuth.findViewById(R.id.tx_auth);
                    txAuth.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            requestSendValidCode();
                        }
                    });
                    layPager.pushNewContent(layPartAuth);
                    hTextView.animateText(getContext().getString(R.string.register_input_auth));
                    isPhoneAndInviteChecked = true;
                    currStep = STEP_AUTH;

                    if (!isAuthCodeChecked) {
                        if (countdownTime > 0) {
                            refreshValidCountdown();
                        } else {
                            requestSendValidCode();
                        }
                    }
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    /**
     * 验证码短信获取重置倒计时 默认为60秒 {@link RegisterLayout#DEFAULT_COUNTDOWN}
     */
    private void refreshValidCountdown() {
        txAuth.setText(getContext().getString(R.string.register_retry_valicode, countdownTime));
        txAuth.removeCallbacks(runRefreshAuthCountdown);
        txAuth.postDelayed(runRefreshAuthCountdown, 1000);
    }

    private Runnable runRefreshAuthCountdown = new Runnable() {
        @Override
        public void run() {
            countdownTime--;
            if (countdownTime <= 0) {
                txAuth.setText(R.string.register_get_valicode);
                txAuth.setEnabled(true);
            } else {
                refreshValidCountdown();
            }
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (animator != null) {
            animator.cancel();
            animator = null;
        }
    }


    public boolean dealBackPressed() {
        if (!layPager.isOnlyOnePageOrEmpty()) {
            layPager.popToLastContent();
            return true;
        }
        return false;
    }
}
